<?php
namespace app\index\controller;
use app\common\logic\UsersLogic;
use app\common\logic\OrderLogic;
use app\common\logic\GoodsLogic;
use app\index\model\PackModel;
use app\common\model\UserModel;
use think\Controller;
use think\Verify;

class User extends Base
{

	public function _initialize() 
	{	
		$this->user = array();
		$this->user_id = 0;
         parent::_initialize();
         if(session('?user'))
        {
            $session_user = session('user');
            $user = db('users')->where("user_id", $session_user['user_id'])->find();
            $level = db('user_level')->getField('level_id,level_name');
            $user['level']=$level[$user['level']];
            session('user',$user);  //覆盖session 中的 user     
            $this->user = $user;
            $this->user_id = $user['user_id']; 
        }else{
            $nologin = array('login','register','logout','vertify','forget','repwd','repass','activate');
            if(!in_array(ACTION_NAME,$nologin)){
                $this->redirect('Index/User/login');
        		exit;
        	}
        }
        $this->assign('user',$this->user); //存储用户信息
        $this->assign('user_id',$this->user_id);     
    }

    public function index()
    {
        return $this->fetch();
    }

    /**
     * 用户信息
     */
    public function message(){
        return $this->fetch();
    }

     /**
     * 用户设置
     */
    public function set(){
        if (IS_POST) {
            $data = input('post.');
            $head_pic = M('users')->where(['user_id'=>$this->user_id])->getField('head_pic');
            if (isset($data['password'])&&isset($data['repass'])) {
                if ($data['password']!=$data['repass']) {
                    $this->ajaxReturn(['status'=>0,'msg'=>'两次密码并不一致']);
                }else{
                    unset($data['repass']);
                    $data['password'] = encrypt($data['password']);
                }
            }
            
            if (isset($data['email'])) {
                if (M('users')->where(['email'=>$data['email'],'user_id'=>['neq',$this->user_id]])->count()) {
                    $this->ajaxReturn(['status'=>0,'msg'=>'邮箱已存在']);
                }else{
                    $data['email_validated'] = 0; //修改邮箱，需要重新验证绑定
                }  
            }
            $res = M('users')->where(['user_id'=>$this->user_id])->save($data);
            if (isset($data['file'])&&$res) {
                unlink('.'.$head_pic);//删除历史头像
            }
            $this->ajaxReturn(['status'=>1,'msg'=>'修改成功','action'=>'']);
        }
        return $this->fetch();
    }

    public function upload()
    {
        if (IS_POST) {
            // 获取表单上传文件 例如上传了001.jpg
            $file = request()->file('file');
            // 移动到框架应用根目录/public/uploads/ 目录下
            if($file){
                $info = $file->move(ROOT_PATH . 'public' . DS . 'upload/avatar');
                if($info){
                    // 成功上传后 获取上传信息
                   $return = array('status'=>1,'msg'=>'上传成功','url'=>'/upload/avatar/'.$info->getSaveName());
                }else{
                    // 上传失败获取错误信息
                    $return = array('status'=>1,'msg'=>$file->getError(),'result'=>''); 
                }
                $this->ajaxReturn($return);
            }
        }
    }

    /**
     * 用户设置
     */
    public function activate(){
        $token = input('token');
        if ($token) {
            $user = get_user_info($token,1);
            if ($user) {
            	$res = db('users')->where(['token'=>$token])->setField(['email_validated'=>1]);
            	$newtoken = md5(time().mt_rand(1,999999999));
	            db('users')->where(['user_id'=>$user['user_id']])->setField(['token'=>$newtoken]); //更新token
                $user = get_user_info($newtoken,1);
                session('user',$user);
                setcookie('lazada_user_id',$user['user_id'],null,'/');
                setcookie('lazada_uname',urlencode($user['nickname']),null,'/');
                setcookie('cn',0,time()-3600,'/');
	           	$this->redirect(url('Index/User/activate'));
            }else{
                $this->error('抱歉！邮箱激活失败',url('Index/User/set'));
            }
        }
        return $this->fetch();
    }



    /**
     * 用户余额充值
     */
    public function recharge(){
        if(IS_POST){
            $user = session('user');
            $data['user_id'] = $this->user_id;
            $data['nickname'] = $user['nickname'];
            $data['account'] = input('account');
            $data['order_sn'] = 'recharge'.get_rand_str(10,0,1);
            $data['ctime'] = time();
            $order_id = M('recharge')->insert($data,false,true);
            if($order_id){
                $url = url('Payment/getPay',array('pay_radio'=>input('pay_radio'),'order_id'=>$order_id));
                $this->redirect($url);
            }else{
                $this->error('提交失败,参数有误!');
            }
        }
        return $this->fetch();
    }

    /**
     * 余额充值记录
     */
    public function rechargeLog(){
        
        $where = [];
        if(IS_POST) {
            $page = input('page');
            $limit = input('limit'); //显示记录数
            $type = input('type');
            $Userlogic = new UsersLogic();

            if($type == 1){
                $result = $Userlogic->get_account_log($this->user_id);  //用户资金变动记录
            }else if($type == 2){
                $result=$Userlogic->get_withdrawals_log($this->user_id);  //提现记录
            }else{
                $result=$Userlogic->get_recharge_log($this->user_id,$page,$limit);  //充值记录
            }
            $this->ajaxReturn($result);    
            
        }
        return $this->fetch('rechargeLog');
    }

     //删除未支付充值记录
    public function rechargeLogDel(){
        if (IS_POST) {
            $id = input('id/d','');//主键
            try {
                db('recharge')->where('order_id',$id)->delete();
                $return = ['status'=>1,'msg'=>'删除成功'];
            } catch (Exception $e) {
                $return = ['status'=>1,'msg'=>$e->getMessage()];
            } 
            
        }else{
            $return = ['status'=>1,'msg'=>'非法操作'];
        }
        $this->ajaxReturn($return);
    }





    public function accountLog(){
        if(IS_POST) {
            $where = ['user_id'=>$this->user_id];
            $param = input('post.');
            $account_log = new UserModel();
            $row = $account_log->getAccountLogByWhere($param,$where);
            $count = $account_log->getAccountLogCount($where);
            $return = ['data'=>$row,'code'=>0,'count'=>$count,'msg'=>""];    
            $this->ajaxReturn($return);    
        }
        return $this->fetch('accountLog');
        
    }


    //检测用户签到状态
    public function signStatus(){
        $userSign = db('user_sign')->where(['user_id'=>$this->user_id])->find();
        $config = tpCache('sign');
        $request = \think\Request::instance();
        $token = $request->token();;
        if ($userSign) {
            $signArr = explode(',',$userSign['signtime']);
            if (in_array(date('Y-m-d'), $signArr)) {
                if ((time()-strtotime(end($signArr)))>86000) {
                    $userSign['signcount'] = 0;
                }
                $return = ['status'=>0,'data'=>['days'=>$userSign['signcount'],'experience'=>$config['sign_integral'],'signed'=>true]];  
            }else{
                $return = ['status'=>0,'data'=>['days'=>$userSign['signcount'],'experience'=>$config['sign_integral'],'figned'=>false,'token'=>$token]];
            }
        }else{
            $return = ['status'=>0,'data'=>['days'=>0,'experience'=>$config['sign_integral'],'token'=>$token]];  
        }
        
        $this->ajaxReturn($return);


    }

    //签到操作
    public function signIn(){
        if (!session('?user')) {
            $this->ajaxReturn(['status'=>0,'msg'=>'请登陆']);
        }
        $user_id = $this->user_id;
        $config = tpCache('sign');
        if ($config['sign_on_off'] > 0) {
            $date = date('Y-m-d');
            $map['lastsign'] = $date;
            $map['user_id'] = $user_id;
            $check = db('user_sign')->where($map)->find();
            $check && $this->ajaxReturn(['status' => 0, 'msg' => '您今天已经签过啦！', 'result' => '']);
            $userSign = db('user_sign')->where(['user_id'=>$user_id])->find();
            // var_dump($userSign);exit;
            $integral = $config['sign_integral'];
            $msg = "签到赠送" . $integral . "积分";
            if (!db('user_sign')->where(['user_id' => $user_id])->find()) {
                //第一次签到
                $data = [];
                $data['user_id'] = $this->user_id;
                $data['signtotal'] = 1;
                $data['lastsign'] = $date;
                $data['cumtrapz'] = $config['sign_integral'];
                $data['signtime'] = "{$date}";
                $data['signcount'] = 1;
                $data['thismonth'] = $config['sign_integral'];
    
                if (db('user_sign')->save($data)) {
                    $status = ['status'=>1,'data'=>['days'=>1,'experience'=>$config['sign_integral'],'signed'=>true]];
                    // accountLog($this->user_id, 0,$integral,$msg);
                } else {
                    $status = ['status' => 0, 'msg' => '签到失败!', 'result' => ''];
                }
                $this->ajaxReturn($status);
            } else {
                $update_data = array(
                    'signtotal' => ['exp', 'signtotal+' . 1], //累计签到天数            
                    'lastsign' => ['exp', "'$date'"], //最后签到时间    
                    'cumtrapz' => ['exp', 'cumtrapz+' . $config['sign_integral']], //累计签到获取积分
                    'signtime' => ['exp', "CONCAT_WS(',',signtime ,'$date')"], //历史签到记录
                    'signcount' => ['exp', 'signcount+' . 1], //连续签到天数
                    'thismonth' => ['exp', 'thismonth+' . $config['sign_integral']], //本月累计积分
                );

                $daya = db('user_sign')->where('user_id', $user_id)->value('lastsign');    //上次签到时间
                $dayb = date("Y-m-d", strtotime($date) - 86400);                                   //今天签到时间
                //不是连续签

                if ($daya != $dayb) {
                    $update_data['signcount'] = ['exp', 1];                                       //连续签到天数
                }

                // $mb = date("m", strtotime($date));                                               //获取本次签到月份
                //不是本月签到
                // if (intval($mb) != intval(date("m", strtotime($daya)))) {
                //     $update_data['signcount'] = ['exp', 1];                                      //连续签到天数
                //     $update_data['signtime'] = ['exp', "'$date'"];                                  //历史签到记录;
                //     $update_data['thismonth'] = ['exp', $config['sign_integral']];              //本月累计积分
                // }
                $update = db('user_sign')->where(['user_id' => $user_id])->update($update_data);
                
                (!$update) && $this->ajaxReturn(['status' => 0, 'msg' => '网络异常！', 'result' => '']);
                // accountLog($user_id, 0,$config['sign_integral'],1,'连续签到');

                $signcount = db('user_sign')->where('user_id', $user_id)->value('signcount');
                $integral = $config['sign_integral'];
                //满足额外奖励                     
                if (( $signcount >= $config['sign_signcount']) && ($config['sign_on_off'] > 0)) {
                    db('user_sign')->where(['user_id' => $user_id])->update([
                        'cumtrapz' => ['exp', 'cumtrapz+' . $config['sign_award']],
                        'thismonth' => ['exp', 'thismonth+' . $config['sign_award']]
                    ]);
                    $integral = $config['sign_integral'] + $config['sign_award'];
                    $msg = "签到" . $config['sign_integral'] . "积分，奖励" . $config['sign_award'] . "积分，共" . $integral . "积分";
                    // accountLog($user_id, 0,$config['sign_award'],$msg);
                }
            }
            if ($config['sign_integral'] > 0 && $config['sign_on_off'] > 0) {
                accountLog($user_id, 0, $integral, $msg);
                $status = ['status' => 1,'data'=>['days'=>$signcount,'experience'=>$integral,'signed'=>true]];
            } else {
                $status = ['status' => 0, 'msg' => '签到失败!', 'result' => ''];
            }
            $this->ajaxReturn($status);
        } else {
            $this->ajaxReturn(['status' => 1, 'msg' => '该功能未开启！', 'result' => '']);
        }
        
        // $this->ajaxReturn(['status'=>0,'data'=>['days'=>$userSign['signcount'],'experience'=>$userSign['sign_integral'],'signed'=>true]]);
    }




    

    


    //查询快递公司编码
    public function get_company_code(){
        return $this->fetch();
    }
 
    



    public function login()
    {
        if($this->user_id > 0){
            $this->redirect('Index/User/index');
        }
    	if (IS_POST) {
    		$username = trim(input('post.loginName'));
            $password = trim(input('post.pass'));
            $verify_code = input('post.vercode');
         
            $verify = new Verify();
            if (!$verify->check($verify_code,'user_login'))
            {
                 $res = array('status'=>0,'msg'=>'验证码错误');
                 exit(json_encode($res));
            }
                     
            $logic = new UsersLogic();
            $res = $logic->login($username,$password);
            
            if($res['status'] == 1){
                //查询用户信息之后, 查询用户的等级昵称
                $levelInfo = db("user_level")->field('level_name')->where("level_id",$res['result']['level'])->cache(true)->find();

                $user['token'] = md5(time().mt_rand(1,999999999));
                $data = ['token' => $user['token'], 'last_ip'=>getIP(),'last_login' => time()];
                db('users')->where(['user_id'=>$res['result']['user_id']])->save($data);

                $res['result']['level_name'] =  $levelInfo['level_name'];
                session('user',$res['result']);
                setcookie('lazada_user_id',$res['result']['user_id'],null,'/');
                $nickname = empty($res['result']['nickname']) ? $username : $res['result']['nickname'];
                setcookie('lazada_uname',urlencode($nickname),null,'/');
                setcookie('cn',0,time()-3600,'/');
                // $orderLogic = new OrderLogic();
                // $orderLogic->setUserId($res['result']['user_id']); //登录后将超时未支付订单给取消掉
                // $orderLogic->abolishOrder();
            }
            exit(json_encode($res));
    	}
    	return $this->fetch();
    }

    public function register(){

    	if (IS_POST) {
    		$logic = new UsersLogic();
    		$reg_sms_enable = tpCache('sms.regis_sms_enable');
    		$username = input('post.phone/d');
    		$vercode = input('post.vercode/d');
    		$nickname = input('post.username/s');
    		$password = input('post.pass/s');
    		$password2 = input('post.repass/s');
    		$scene = input('post.scene', 1);
    		$session_id = session_id();


    		if(check_mobile($username)){
                if($reg_sms_enable){   //是否开启注册验证码机制
                    //手机功能没关闭
                    $check_code = $logic->check_validate_code($vercode, $username, $session_id, $scene);
                    if($check_code['status'] != 1){
                        $this->ajaxReturn($check_code);
                    }
                }
            }


    		
    		$data = $logic->reg($username,$nickname,$password,$password2);
            if($data['status'] != 1){
                $this->ajaxReturn($data);
            }
            session('user',$data['result']);
    		setcookie('lazada_user_id',$data['result']['user_id'],null,'/');
            $nickname = empty($data['result']['nickname']) ? $username : $data['result']['nickname'];
            setcookie('lazada_uname',$nickname,null,'/');
            $this->ajaxReturn($data);
            exit;
    	}
    	return $this->fetch();
    }

    public function forget()
    {
        if (IS_AJAX) {
            $data = input();
            if (empty($data['vercodeQuiz'])) {
                $this->ajaxReturn(['status'=>0,'msg'=>'图形验证码不能为空']);
            }
            
            //判断是邮箱找回还是手机找回
            if (array_key_exists('email',$data)) {
                $verify = new Verify();
                if (!$verify->check($data['vercodeQuiz'],'repwd'))
                {
                     $this->ajaxReturn(['status'=>0,'msg'=>'验证码错误']);
                }   
                $info = db('users')->where(['email'=>$data['email'],'email_validated'=>1])->find();
                
                if (empty($info)) {
                    $this->ajaxReturn(['status'=>0,'msg'=>'邮箱不存在或者未激活']);
                }
                $html = <<<EOF
<div id="mailContentContainer" class="qmbox qm_con_body_content qqmail_webmail_only" style="">
    <table border="0" cellpadding="0" cellspacing="0" style="width: 600px; border: 1px solid #ddd; border-radius: 3px; color: #555; font-family: 'Helvetica Neue Regular',Helvetica,Arial,Tahoma,'Microsoft YaHei','San Francisco','微软雅黑','Hiragino Sans GB',STHeitiSC-Light; font-size: 12px; height: auto; margin: auto; overflow: hidden; text-align: left; word-break: break-all; word-wrap: break-word;"> <tbody style="margin: 0; padding: 0;"> <tr style="background-color: #393D49; height: 60px; margin: 0; padding: 0;"> <td style="margin: 0; padding: 0;"> <div style="color: #5EB576; margin: 0; margin-left: 30px; padding: 0;"><a style="font-size: 14px; margin: 0; padding: 0; color: #5EB576; text-decoration: none;" href="http://lazada100.com/" target="_blank" rel="noopener">电商之家</a></div> </td> </tr> <tr style="margin: 0; padding: 0;"> <td style="margin: 0; padding: 30px;"> <p style="line-height: 20px; margin: 0; margin-bottom: 10px; padding: 0;"> 你好，<em style="font-weight: 700;">{$info['nickname']}</em>童鞋，请在30分钟内重置您的密码： </p> <div style=""> <a href="http://lazada100.com/index/user/repwd?token={$info['token']}&key=email&value={$data['email']}" style="background-color: #009E94; color: #fff; display: inline-block; height: 32px; line-height: 32px; margin: 0 15px 0 0; padding: 0 15px; text-decoration: none;" target="_blank" rel="noopener">立即重置密码</a> </div> <p style="line-height: 20px; margin-top: 20px; padding: 10px; background-color: #f2f2f2; font-size: 12px;"> 如果该邮件不是由你本人操作，请勿进行激活！否则你的邮箱将会被他人绑定。 </p> </td> </tr> <tr style="background-color: #fafafa; color: #999; height: 35px; margin: 0; padding: 0; text-align: center;"> <td style="margin: 0; padding: 0;">系统邮件，请勿直接回复。</td> </tr> </tbody> </table>
<style type="text/css">.qmbox style, .qmbox script, .qmbox head, .qmbox link, .qmbox meta {display: none !important;}</style></div>
EOF;
                send_email($data['email'],'电商之家找回密码', $html);//发送邮件
                $this->ajaxReturn(['status'=>1,'msg'=>'已将密码重置地址发送至您的邮箱，请注意查收','url'=>url('user/forget')]);
            }
            if(array_key_exists('phone',$data)){
                $info = db('users')->where(['mobile'=>$data['phone']])->find();
                if (empty($info)) {
                    $this->ajaxReturn(['status'=>0,'msg'=>'手机号码不存在']);
                }
                $session_id = session_id();
                $logic = new UsersLogic();
                $check_code = $logic->check_validate_code($data['vercode'], $data['phone'], $session_id, 1);
                if($check_code['status'] != 1){
                    $this->ajaxReturn($check_code);
                }
                $this->ajaxReturn(['status'=>1,'msg'=>'请求成功','url'=>url('User/repwd',['token'=>$info['token'],'key'=>'mobile','value'=>$info['mobile']])]);
            }
        }
        $type = input('type','forget');
        return $this->fetch($type);
    }

    public function repwd()
    {

        $token = input('token/s','');
        $key = input('key/s','email');
        $value = input('value/s','');
        if (empty($token)) {
            $this->error('抱歉！参数错误！');
        }
        if (empty($value)) {
            $this->error('抱歉！参数错误！');
        }

        $info = db('users')->where(['token'=>$token,$key=>$value])->find();
        if (empty($info)) {
            $this->error('抱歉 记录不存在！');
        }
        $this->assign('info',$info);
        return $this->fetch();
    }

    //更新密码
    public function repass()
    {
        $data = input();
        $verify = new Verify();
        if ($data['pass']!=$data['repass']) {
            $this->ajaxReturn(['status'=>0,'msg'=>'两次密码并不一致']);
        }

        if (!preg_match("/^[a-zA-Z\d_]{6,16}$/", $data['pass'])) {
            $this->ajaxReturn(['status'=>0,'msg'=>'密码格式格式错误（6-16字符 数字字母下划线）']);
        }

        if (!$verify->check($data['vercode'],'user_login'))
        {
             $this->ajaxReturn(['status'=>0,'msg'=>'验证码错误']);
        }
        if (array_key_exists('email',$data)) 
        { //邮件方式更新密码
            $pwd = encrypt(trim($data['pass']));
            $result = db('users')->where(['nickname'=>trim($data['username']),'email'=>$data['email']])->save(['password'=>$pwd]);
            if ($result) {
                $this->ajaxReturn(['status'=>1,'msg'=>'密码成功修改','url'=>url('user/login')]);
            }else{
                $this->ajaxReturn(['status'=>0,'msg'=>'密码修改失败']);
            }
            
        }else{//手机方式更新密码

        }  
    }

    /**
     * 登出
     * @return [type] [description]
     */
    public function logout(){
        setcookie('lazada_uname','',time()-3600,'/');
        setcookie('lazada_user_id','',time()-3600,'/');
        session_unset();
        session_destroy();
        $this->redirect('Index/User/login');
        exit;
    }


     /**
     * 验证码获取
     */
    public function vertify()
    {
        //验证码类型
        $type = input('type') ? input('type') : 'user_login';
        $config = array(
            'fontSize' => 30,
            'length' => 4,
            'useCurve' => false,
            'useNoise' => false,
            'reset' => false,
            'useImgBg' => true,
        );    
        $Verify = new Verify($config);
        $Verify->entry($type);
        exit();
    }
}
